# -*- coding: utf-8 -*-
#
# The Philatelist program is a fork of the OpenNumismat program
# Copyright (c) 2011 - 2024 Vitaly Ignatov (OpenNumismat) <opennumismat@gmail.com>
# Copyright (c) 2021 - 2024 Victor Nabatov (Philatelist) <nabatov.victor@gmail.com>
#

from PySide6.QtGui import QTextDocument
from PySide6.QtCore import QLocale


def stringToMoney(string):
    spaces = ' \t\n\r' + QLocale.system().groupSeparator()
    dp = [QLocale.system().decimalPoint(), ]
    if dp[0] == ',' and '.' != QLocale.system().groupSeparator():
        dp.append('.')

    value_began = False
    money = '0'
    for c in string:
        if c in '0123456789':
            money = money + c
            value_began = True

        elif c == '-' and not value_began:
            money = '-0'

        elif c in dp:
            money += '.'

        elif c in spaces:
            continue

        else:
            if value_began:
                break

    try:
        return float(money)

    except ValueError:
        return 0.


def numberWithFraction(string, enabled=True):
    if string and enabled:
        if len(string) > 2:
            string = string.replace(',', '.')
            try:
                if ".25" in string:
                    string = string.replace('.25', '¼')

                if ".5" in string:
                    string = string.replace('.5', '½')

                if ".75" in string:
                    string = string.replace('.75', '¾')

            except (ValueError, TypeError):
                pass

            return string

        return string

    return string, True


def htmlToPlainText(text):
    RICH_PREFIX = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" '\
                  '"https://www.w3.org/TR/REC-html40/strict.dtd">'
    if text.startswith(RICH_PREFIX):
        document = QTextDocument()
        document.setHtml(text)
        text = document.toPlainText()

    return text


def _compareYearStrings(left, right):
    if left and left[0] == '-' and right and right[0] == '-':
        left_year = 0
        right_year = 0
        for c in left[1:]:
            if c.isdigit():
                left_year = left_year * 10 + (ord(c) - ord('0'))
            else:
                break

        for c in right[1:]:
            if c.isdigit():
                right_year = right_year * 10 + (ord(c) - ord('0'))
            else:
                break

        if left_year != right_year:
            # Invert comparing for negative years
            return -(left_year - right_year)

    if left < right:
        return -1
    # elif left == right:
    #    return 0
    else:
        return 1


def compareYears(left, right):
    if isinstance(left, str):
        right = str(right)
        return _compareYearStrings(left, right)

    elif isinstance(right, str):
        left = str(left)
        return _compareYearStrings(left, right)

    return left - right
